/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.sorbonne.inf1.tp3.model.distant.protocole;

import Exceptions.*;
import Objet.Message;
import communication.InterfaceTransport;
import fr.sorbonne.inf1.tp3.model.distant.protocole.exception.*;

/**
 *
 * @author Rich
 */
public class ProtocoleClient implements InterfaceProtocoleClient{
    
    private InterfaceTransport t;
    private Message msg;

    public ProtocoleClient(InterfaceTransport pTrans) {
        this.t = pTrans;
    }

    @Override
    public void demandeCalculAnnuite(Double pMontant, int pNb_annee, Double pTaux) throws SendProtocolException {
        try {
            msg = new Message(1, pMontant, pTaux, pNb_annee, -1, -1);
            t.envoyer(msg);

        } catch (SendTransportException ex) {
            throw new SendProtocolException();
        }
    }

    @Override
    public void demandeCalculNbAnnees(Double pMontant, Double pTaux, int pAnnuite) throws SendProtocolException {
        try {
            msg = new Message(2, pMontant, pTaux, -1, pAnnuite, -1);
            t.envoyer(msg);

        } catch (SendTransportException ex) {
            throw new SendProtocolException();
        }
    }

    @Override
    public Double recuperer_resultat() throws AnnuiteException, ClassCastException,MontantException, TauxException,NbAnneesException,CalculAnnuiteException, ReceiveProtocolException  {

        int codeStat;
        Double result = 0.0;
        try {
            msg = (Message) t.recevoir();
        } catch (ReceiveTransportException ex) {
            throw new ReceiveProtocolException();
        }
        codeStat = msg.getStatus();

        if (codeStat == 0) {
            result = msg.getMontant();  
        } else if (codeStat == 2){
            throw new MontantException();
        } else if (codeStat == 3){
            throw new TauxException();
        } else if (codeStat == 4){
            throw new AnnuiteException();
        } else if (codeStat == 5){
            throw new NbAnneesException();
        } else if (codeStat == 6){
            throw new ClassCastException();
        } else if (codeStat == 7){
            throw new CalculAnnuiteException();
        } 

        return result;
    }

    @Override
    public void fermer() throws CloseProtocolException {
        try {
            t.fermer();
        } catch (CloseTransportException ex) {
            throw new CloseProtocolException();
        }
    }
    
}
